package com.giraffe.aiochat.server.manager;

import java.nio.channels.AsynchronousSocketChannel;
import java.util.Collections;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.giraffe.aiochat.model.User;

public class ClientManager {

    private static final Logger logger = LoggerFactory.getLogger(ClientManager.class);

    private static final ClientManager instance = new ClientManager();
    
    private final static Map<AsynchronousSocketChannel, User> users = new ConcurrentHashMap<>();

    private ClientManager() {
        // 私有构造函数
    }

    public static ClientManager getInstance() {
        return instance;
    }

    public void addClient(AsynchronousSocketChannel channel,User user) {
        if(users.containsKey(channel)){
            return;
        }
        users.put(channel, user);
    }

    public User getUser(AsynchronousSocketChannel channel) {
        return users.get(channel);
    }

    public User removeClient(AsynchronousSocketChannel channel) {
        User user  = closeChannel(channel);
        users.remove(channel);
        if (user != null) {
            logger.info("客户端断开连接: {} (昵称: {})", user.getClientAddress(), user.getName());
        }
        return user;
        
    }

    public String getNickname(AsynchronousSocketChannel channel) {
        User user = users.get(channel);
        return user != null ? user.getName() : null;
    }

    public Map<AsynchronousSocketChannel, User> getClients() {
        return Collections.unmodifiableMap(users);
    }

    private User closeChannel(AsynchronousSocketChannel clientChannel) {
        try {
            if (clientChannel.isOpen()) {
                logger.info("正在关闭客户端通道: {}", clientChannel.getRemoteAddress());
                clientChannel.close();
                return users.get(clientChannel);
            }
        } catch (Exception e) {
            logger.error("关闭客户端通道时发生错误", e);
        }
        return null;
    }

    
}